<?php
// +----------------------------------------------------------------------
// | 悟空信息技术有限公司
// +----------------------------------------------------------------------
// | Copyright (c)2016 http://www.wkidt.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: wkidt team Tx <admin@wkidt.com> 2018/5/12 11:32
// +----------------------------------------------------------------------
// | Readme: 预约模型
// +----------------------------------------------------------------------


namespace app\mobile\model;

use think\Db;
use Wkidt\think5\model\Model;
use EasyWeChat\Factory;

class AppointmentModel extends Model
{


    /**
     * 获取预约项目列表
     * @param $shop_id
     * *@param $day
     * @return array
     * @throws \think\exception\PDOException
     */
    public  function  getAppointmentList($day,$shop_id){

        if(empty($shop_id)){
            return ['code' => 'ERROR', 'info' =>'没有店铺id'];
        }
        $where['shop_id'] = $shop_id;
        $data = Db::name('appointment_project')->order('id desc')->where($where)->paginate();
        $item = $data->items();
        if($item){
            return ['data' =>$item, 'page' => $data->getPageInfo()];
        }else{
            return null;
        }

    }

    /**
     * 获取预约时间
     * @param $shop_id
     * @return array
     * @throws \think\exception\PDOException
     */
    public  function  getAppointmentDate($shop_id){

        if(empty($shop_id)){
            return ['code' => 'ERROR', 'info' =>'没有店铺id'];
        }

        $d_time=strtotime(date('Y-m-d'));//当天的时间戳
        $this->automationAddAppointmentDate($shop_id,$d_time);//自动添加预约时间

       $appointment_date=Db::name('appointment_date')->where(['shop_id'=>$shop_id,'a_date'=>['egt',$d_time]])->select();
        return ['info' =>'获取预约时间成功！','data'=> $appointment_date];
    }


    /**
     * 获取预约项目列表
     * @param $ad_id
     * @return array
     */
    public  function  getAppointmentDateDot($ad_id,$shop_id,$uid){

        if(empty($ad_id)){
            return ['code' => 'ERROR', 'info' =>'没有预约时间id'];
        }

        $data=Db::name('appointment_date_dot')->where(['a_date_id'=>$ad_id])->select();

        foreach ($data as $key => $item){
            $member=Db::name('member')->where('uid',$uid)->find();
            // 判断会员是不是VIP会员
            $where['uid']=$uid;
            $where['dot_id']=$item['dot_id'];
            $where['status'] =1;
            $res = Db::name('member_appointment')->where($where)->find();
            //如果预约过该项目
            if($res){
                $data[$key]['member_allow_appointment'] = 0;
            }else{
                $data[$key]['member_allow_appointment'] = 1;
            }
            if(in_array($member['member_group'],[1,2,3,4,5])){

                if($item['appointment_sum']<=$item['already_appointment']){
                    $data[$key]['member_allow_appointment'] = 0;
                }
            }else{
                if($item['other_allow']<=$item['already_appointment']){
                    $data[$key]['member_allow_appointment'] = 0;
                }
            }
        }
        return ['info' =>'获取预约时间成功！','data'=> $data];

    }


    /**
     * 用户预约项目
     * @param $shop_id
     * @param $dot_id
     * @param $card_id
     * @return array
     */
    public  function  addAppointment($dot_id,$uid){

        $member = Db::name('member')->where('uid',$uid)->find();
        if($member){
            $item['status']=1;
            $item['dot_id']=$dot_id;
            $item['uid']=$member['uid'];
            $item['openid']=$member['openid'];
            $item['shop_id']=1;
            $item['check_status']=0;
            $item['add_time']=time();
            $query['uid']=$uid;
            $query['dot_id']=$dot_id;
            $query['status']=1;
            if(Db::name('member_appointment')->where($query)->find()){
                return ['code' => 'ERROR', 'info' =>'已经预约过了','data' =>array()];
            }else{
                $res= Db::name('member_appointment')->strict(true)->insertGetId($item);


                // 更新预约项目预约人数
                $appointment_date_dot = Db::name('appointment_date_dot')->where('dot_id',$item['dot_id'])->find();

                if ($appointment_date_dot['appointment_sum'] > $appointment_date_dot['already_appointment']){
                    Db::name('appointment_date_dot')->where('dot_id',$dot_id)->setInc('already_appointment',1);
                }else{
                    return ['code' => 'ERROR', 'info' =>'预约满了','data' =>array()];
                }

                if($res){
                    $memberInfo = $member->where('uid',$uid)->find();
                    // 推送模版消息
                    $app = Factory::officialAccount(config("EasyWechetConfig"));
                    $rs = $app->template_message->getPrivateTemplates();

                    $sent_data['touser'] = $memberInfo['openid'];
                    $sent_data['template_id'] = 'Y8pfWNYbeeSgnNutd63t2Es9OhSNIv7n0s84rfGhpkY';
                    $sent_data['url'] = 'http://oscar.wkidt.com/#/';
                    $sent_data['data']['first'] = "您卡号为".$memberInfo['member_card']."的会员卡预约成功";
                    $sent_data['data']['keyword1'] =$appointment_date_dot['title'];
                    $sent_data['data']['keyword2'] = '课程时间：'.date("Y-m-d", $appointment_date_dot['daytimes']).' : '.$appointment_date_dot['startTime'].'-'.$appointment_date_dot['endTime'];
                    $sent_data['data']['remark'] = '奥斯卡全体员工期待您的光临';

                    $app->template_message->send($sent_data);
                    return ['data' =>$res,];
                }else{
                    return ['code' => 'ERROR', 'info' =>'没有数据','data' =>array()];
                }

            }

        }else{
            return ['code' => 'ERROR', 'info' =>'会员不存在','data' =>array()];
        }

    }



    /**
     * 自动添加预约时间
     * @param $shop_id
     * @return array
     * @throws \think\exception\PDOException
     */
    private  function  automationAddAppointmentDate($shop_id,$d_time){

        $appointment_date=Db::name('appointment_date')->where(['shop_id'=>$shop_id,'a_date'=>['egt',$d_time]])->select();
        $sum=count($appointment_date);
        if($sum<7){
            if($sum==0){
                $a_date=$d_time;
            }else {
                $a_date = $appointment_date[$sum - 1]['a_date']+(24*60*60);
            }

            for($i=$sum;$i<=6;$i++){
                if($i>$sum){
                    $a_date =$a_date+(24*60*60);
                }
                $data['shop_id']=$shop_id;
                $data['a_date']=$a_date;
                $data['add_time']=time();
                Db::name('appointment_date')->insert($data);
            }
        }

    }

    /**
     *获取用户预约列表
     */
    public  function  getMemberAppointment($uid){


        $today = strtotime(date("Y-m-d"),time());

        $list=Db::name('member_appointment')
            ->alias('ma')
            ->join('wk_appointment_date_dot dot','ma.dot_id = dot.dot_id','left')
            ->join('wk_member member','member.uid = ma.uid','left')
            ->where('ma.uid',$uid)
            ->where('dot.daytimes','>=',$today)
            ->where('ma.status',1)
            ->order(['ma.ma_id'=>'desc'])
            ->field('ma.ma_id,ma.uid,ma.status,ma.check_status,ma.add_time,dot.title,dot.startTime,dot.endTime,dot.daytimes,member.realName,member.phone,member.member_group_title,member.member_card')
            ->paginate();

        $data=$list->items();
        if($data){
            return ['data' =>$data, 'page' => $list->getPageInfo()];
        }else{
            return ['code'=>'error','data' =>[]];
        }
    }


    /**
     * 取消预约
     * @param $id
     * @return array
     */
    public  function  cancelAppointment($id){
        if(empty($id)){
            return ['code' => 'ERROR', 'info' =>'没有预约id'];
        }

        if(Db::name('member_appointment')->where('ma_id',$id)->update(['status'=>0])){
            $dot_id = Db::name('member_appointment')->where('ma_id',$id)->value('dot_id');
            Db::name('appointment_date_dot')->where('dot_id',$dot_id)->setDec('already_appointment',1);
            return ['code' => 'SUCCESS','info' =>'取消预约成功！'];
        }else{
            return ['code' => 'ERROR', 'info' =>  '取消预约失败'];
        }
    }
}